#include "CSerialPort.h"
#include <QSerialPortInfo>
#include <QDebug>

CSerialPort::CSerialPort(QObject *parent) : QObject(parent)
{
    //初始化串口类
    m_serialPort = new QSerialPort();
}

QVector<QString> CSerialPort::getPortNamelist()
{
     QVector<QString> ports;
     foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
            ports.push_back(info.portName());
     }
     return ports;
}

void CSerialPort::openPort(QString port)
{
    //串口打开的先关闭
    if(m_serialPort->isOpen()){
        m_serialPort->clear();
        m_serialPort->close();
    }
    m_serialPort->setPortName(port);
    m_serialPort->setBaudRate(QSerialPort::Baud9600);//设置波特率和读写方向
    m_serialPort->setDataBits(QSerialPort::Data8);      //数据位为8位
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
    m_serialPort->setParity(QSerialPort::NoParity); //无校验位
    m_serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
    //已readwrite模式打开
    if(!m_serialPort->open(QIODevice::ReadWrite)){
        qDebug() << "打开失败";
        return;
    }
    qDebug() << "打开成功";
    currentPort = port;
    connect(m_serialPort,&QSerialPort::readyRead,this,&CSerialPort::receiveInfo);
}

bool CSerialPort::portIsOpen()
{
    return m_serialPort->isOpen();
}

bool CSerialPort::closePort()
{
    if(m_serialPort->isOpen()){
        m_serialPort->clear();
        m_serialPort->close();
        return true;
    }
    return false;
}

qint64 CSerialPort::sendMsg(QString msg)
{
    QByteArray by = msg.toLocal8Bit().data();
    by += 0x0d;
    by += 0x0a;
    qint64 byNum = m_serialPort->write(by);
    return byNum;
}

QString CSerialPort::getCurrentPort()
{
    return currentPort;
}

void CSerialPort::receiveInfo()
{
    QByteArray info = m_serialPort->readAll();
    qDebug() << info;
    emit getInfo(info);
}
